﻿using System;
using System.Collections;
using System.IO;
using System.Text;

namespace YioksPlanEditor.Tools
{
    public class FileTool
    {
        #region 文件夹管理

        #region 创建文件夹

        /// <summary>
        /// 创建文件夹
        /// </summary>
        public static bool Dir_Create(string path)
        {
            try
            {
                var dir = new DirectoryInfo(path);
                if (!dir.Exists)
                    dir.Create();
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }

        #endregion

        #endregion

        #region 文件管理

        #region 将内容保存成为一个文件

        /// <summary>
        /// 将内容保存成为一个文件
        /// </summary>
        /// <param name="filePath">文件路经</param>
        /// <param name="content">文件内容</param>
        /// <returns>反回成功或失败</returns>
        public static bool File_Save(string filePath, string content)
        {
            string path = @filePath;

            var dir = new DirectoryInfo(Path.GetDirectoryName(filePath));
            if (!dir.Exists)
                dir.Create();

            try
            {
                using (var sw = File.CreateText(path))
                {
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion

        #region 将内容保存成为一个文件

        /// <summary>
        /// 将内容保存成为一个文件
        /// </summary>
        /// <param name="filePath">文件路经</param>
        /// <param name="content">文件内容</param>
        /// <param name="encoding"></param>
        /// <returns>反回成功或失败</returns>
        public static bool File_Save(string filePath, string content, Encoding encoding)
        {
            var path = @filePath;
            try
            {
                using (var sw = new StreamWriter(path, false, encoding))
                {
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                    return true;
                }
            }
            catch (Exception)
            {

                return false;
            }
        }

        #endregion

        #region 读取文件内容

        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="filePath">文件位置</param>
        /// <returns></returns>
        public static string File_Read(string filePath)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    var sr = File.OpenText(filePath);
                    var output = new StringBuilder();
                    string rl;
                    while ((rl = sr.ReadLine()) != null)
                    {
                        output.Append(rl + "\r\n");
                    }
                    var confignnr = output.ToString();
                    sr.Close();
                    return confignnr;
                }
                catch (Exception)
                {

                    return "";
                }
            }
            else
            {
                return "";
            }
        }

        #endregion

        #region 读取文件内容 指定编码格式

        /// <summary>
        /// 读取文件内容
        /// </summary>
        public static string File_Read(string filePath, Encoding encoding)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    StreamReader sr = new StreamReader(filePath, encoding);
                    string info = "";
                    while (sr.Peek() > -1)
                    {
                        info = info + sr.ReadToEnd() + "\r\n";
                    }
                    sr.Close();
                    return info;
                }
                catch (Exception)
                {

                    return "";
                }
            }
            else
            {
                return "";
            }
        }

        #endregion

        #region 更改文件属性

        /// <summary>
        /// 更改文件属性
        /// </summary>
        /// <param name="filePath">文件路经</param>
        /// <param name="type">属性</param>
        /// <returns>反回成功或失败</returns>
        public static bool File_Attribute(string filePath, FileAttributes type)
        {
            var path = @filePath;
            try
            {
                var fileInfo = new FileInfo(path);
                fileInfo.Attributes |= type;
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }

        #endregion

        #region 将内容添加一个文件

        /// <summary>
        /// 将内容添加一个文件
        /// </summary>
        /// <param name="filePath">文件路经</param>
        /// <param name="content">文件内容</param>
        /// <returns>反回成功或失败</returns>
        public static bool File_SaveAdd(string filePath, string content)
        {
            var path = @filePath;
            try
            {
                if (File.Exists(path))
                {
                    var sw = File.AppendText(path);
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                    return true;
                }
                else
                {
                    return File_Save(filePath, content);
                }
            }
            catch (Exception)
            {

                return false;
            }
        }

        #endregion

        #endregion

        #region 配置文件

        //读取本地配置文件
        /// <summary>
        /// 读取本地配置文件
        /// </summary>
        /// <param name="filepath">配置文件</param>
        /// <param name="name">配置标题</param>
        /// <returns></returns>
        public static Hashtable ReadConfig(string filepath, string name)
        {
            Hashtable htConfig = new Hashtable();
            name = "[" + name + "]";
            if (File.Exists(filepath))
            {
                try
                {
                    var sr = File.OpenText(filepath);
                    string rl;
                    while ((rl = sr.ReadLine()) != null)
                    {
                        if (rl == name)
                        {
                            while ((rl = sr.ReadLine()) != null)
                            {
                                if (rl.Contains("[") && rl.Contains("]"))
                                {
                                    sr.Close();
                                    return htConfig;
                                }
                                else
                                {
                                    if (rl.Contains("="))
                                    {
                                        string[] r2 = new string[2];
                                        r2[0] = rl.Substring(0, rl.IndexOf("=", StringComparison.Ordinal));
                                        r2[1] = rl.Substring(rl.IndexOf("=", StringComparison.Ordinal) + 1);
                                        htConfig[r2[0]] = r2[1];
                                    }
                                }
                            }
                        }
                    }
                    sr.Close();
                }
                catch (Exception)
                {

                    //PublicFunction.MessigeBos(ex.ToString());
                }
            }
            return htConfig;
        }

        //删除本地配置文件 指定的配置及属性
        /// <summary>
        /// 删除本地配置文件 指定的配置及属性
        /// </summary>
        /// <param name="filepath">配置文件</param>
        /// <param name="name">配置标题</param>
        /// <returns></returns>
        public static void DelectConfig(string filepath, string name)
        {
            ReadConfig(filepath, name);
            File.Delete(filepath + ".bak");
            if (File.Exists(filepath))
            {
                try
                {
                    var sr = File.OpenText(filepath);
                    string rl;
                    name = "[" + name + "]";
                    while ((rl = sr.ReadLine()) != null)
                    {
                        if (rl == name)
                        {
                            bool f = false;
                            while ((rl = sr.ReadLine()) != null)
                            {
                                if (rl.Contains("[") && rl.Contains("]"))
                                {
                                    File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    f = true;
                                }
                                else
                                {
                                    if (f)
                                    {
                                        File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    }
                                }
                            }
                        }
                        else
                        {
                            File.AppendAllText(filepath + ".bak", rl + "\r\n");
                        }
                    }
                    sr.Close();
                    File.Delete(filepath);
                    File.Move(filepath + ".bak", filepath);
                }
                catch (Exception)
                {

                }
            }
        }

        //删除本地配置文件指定配置的属性
        /// <summary>
        /// 删除本地配置文件指定配置的属性
        /// </summary>
        /// <param name="filepath">配置文件</param>
        /// <param name="name">配置标题</param>
        /// <param name="arrList">配置性性列表</param>
        /// <returns></returns>
        public static void DelectConfig(string filepath, string name, ArrayList arrList)
        {
            Hashtable ht_config = ReadConfig(filepath, name);
            File.Delete(filepath + ".bak");
            if (File.Exists(filepath))
            {
                try
                {
                    StreamReader sr = File.OpenText(filepath);
                    string rl;
                    name = "[" + name + "]";
                    while ((rl = sr.ReadLine()) != null)
                    {
                        if (rl == name)
                        {
                            bool f = false;
                            File.AppendAllText(filepath + ".bak", name + "\r\n");
                            while ((rl = sr.ReadLine()) != null)
                            {
                                if (rl.Contains("[") && rl.Contains("]"))
                                {
                                    File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    f = true;
                                }
                                else
                                {
                                    if (f)
                                        File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    else
                                    {
                                        for (int i = 0; i < arrList.Count; i++)
                                        {
                                            if (!rl.Contains(arrList[i] + "="))
                                                File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            File.AppendAllText(filepath + ".bak", rl + "\r\n");
                        }
                    }
                    sr.Close();
                    File.Delete(filepath);
                    File.Move(filepath + ".bak", filepath);
                }
                catch (Exception)
                {

                }
            }
        }

        //删除本地配置文件指定配置的属性
        /// <summary>
        /// 删除本地配置文件指定配置的属性
        /// </summary>
        /// <param name="filepath">配置文件</param>
        /// <param name="name">配置标题</param>
        /// <param name="configName">配置性性列表</param>
        /// <returns></returns>
        public static void DelectConfig(string filepath, string name, string configName)
        {
            Hashtable ht_config = ReadConfig(filepath, name);
            File.Delete(filepath + ".bak");
            if (File.Exists(filepath))
            {
                try
                {
                    StreamReader sr = File.OpenText(filepath);
                    string rl;
                    name = "[" + name + "]";
                    while ((rl = sr.ReadLine()) != null)
                    {
                        if (rl == name)
                        {
                            bool f = false;
                            File.AppendAllText(filepath + ".bak", name + "\r\n");
                            while ((rl = sr.ReadLine()) != null)
                            {
                                if (rl.Contains("[") && rl.Contains("]"))
                                {
                                    File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    f = true;
                                }
                                else
                                {
                                    if (f)
                                        File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    else
                                    {
                                        if (!rl.Contains(configName + "="))
                                            File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    }
                                }
                            }
                        }
                        else
                        {
                            File.AppendAllText(filepath + ".bak", rl + "\r\n");
                        }
                    }
                    sr.Close();
                    File.Delete(filepath);
                    File.Move(filepath + ".bak", filepath);
                }
                catch (Exception)
                {

                }
            }
        }

        //保存配置至本地配置文件
        /// <summary>
        /// 保存配置至本地配置文件
        /// </summary>
        /// <param name="filepath">配置文件</param>
        /// <param name="name">配置标题</param>
        /// <param name="ht">配置内容</param>
        /// <returns></returns>
        public static bool SaveConfig(string filepath, string name, Hashtable ht)
        {
            Hashtable htConfig = ReadConfig(filepath, name);
            File.Delete(filepath + ".bak");
            ArrayList akeys = new ArrayList(ht.Keys);
            foreach (string skey in akeys)
            {
                htConfig[skey] = ht[skey];
            }
            if (File.Exists(filepath))
            {
                try
                {
                    StreamReader sr = File.OpenText(filepath);
                    string rl;
                    name = "[" + name + "]";
                    bool s = true;
                    while ((rl = sr.ReadLine()) != null)
                    {
                        if (rl == name)
                        {
                            s = false;
                            bool t = true;
                            bool f = false;
                            while ((rl = sr.ReadLine()) != null)
                            {
                                if (rl.Contains("[") && rl.Contains("]"))
                                {
                                    File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    f = true;
                                }
                                else
                                {
                                    if (t)
                                    {
                                        akeys = new ArrayList(htConfig.Keys);
                                        File.AppendAllText(filepath + ".bak", name + "\r\n");
                                        foreach (string skey in akeys)
                                        {
                                            File.AppendAllText(filepath + ".bak",
                                                skey + "=" + htConfig[skey].ToString() + "\r\n");
                                        }
                                        t = false;
                                    }
                                    if (f)
                                    {
                                        File.AppendAllText(filepath + ".bak", rl + "\r\n");
                                    }
                                }
                            }
                        }
                        else
                        {
                            File.AppendAllText(filepath + ".bak", rl + "\r\n");
                        }
                    }
                    sr.Close();
                    if (s)
                    {
                        akeys = new ArrayList(htConfig.Keys);
                        File.AppendAllText(filepath + ".bak", name + "\r\n");
                        foreach (string skey in akeys)
                        {
                            File.AppendAllText(filepath + ".bak", skey + "=" + htConfig[skey].ToString() + "\r\n");
                        }
                    }
                    File.Delete(filepath);
                    File.Move(filepath + ".bak", filepath);
                }
                catch (Exception)
                {
                    //if (PublicVariables.DebugLevel > 2) { MessageBox.Show(ex.ToString()); }
                    //PublicFunction.MessigeBos(EX.ToString());
                }
            }
            else
            {
                akeys = new ArrayList(htConfig.Keys);
                name = "[" + name + "]";
                File.AppendAllText(filepath, name + "\r\n");
                foreach (string skey in akeys)
                {
                    File.AppendAllText(filepath, skey + "=" + htConfig[skey].ToString() + "\r\n");
                }
            }
            return true;
        }

        #endregion

        #region 复制文件

        public static bool File_Copy(string fileFrom, string fileTo)
        {
            try
            {
                var dir = new DirectoryInfo(Path.GetDirectoryName(fileTo));
                if (!dir.Exists)
                    dir.Create();

                File.Copy(fileFrom, fileTo, true);
            }
            catch
            {
                return false;
            }
            return true;
        }

        #endregion

        #region 复制文件

        public static bool File_Move(string fileFrom, string fileTo)
        {
            try
            {
                var dir = new DirectoryInfo(Path.GetDirectoryName(fileTo));
                if (!dir.Exists)
                    dir.Create();

                File.Move(fileFrom, fileTo);
            }
            catch
            {
                return false;
            }
            return true;
        }

        #endregion

        /// <summary>
        /// 目录复制
        /// </summary>
        /// <param name="srcDir"></param>
        /// <param name="tgtDir"></param>
        public static bool CopyDirectory(string srcDir, string tgtDir)
        {
            var succes = true;
            try
            {
                var source = new DirectoryInfo(srcDir);
                var target = new DirectoryInfo(tgtDir);

                if (target.FullName.StartsWith(source.FullName, StringComparison.CurrentCultureIgnoreCase))
                {
                    succes = false;
                }

                if (!source.Exists)
                {
                    return false;
                }

                if (!target.Exists)
                {
                    target.Create();
                }

                var files = source.GetFiles();

                for (var i = 0; i < files.Length; i++)
                {
                    File.Copy(files[i].FullName, target.FullName + "/" + files[i].Name, true);
                }

                var dirs = source.GetDirectories();

                for (var j = 0; j < dirs.Length; j++)
                {
                    succes = succes && CopyDirectory(dirs[j].FullName, target.FullName + "/" + dirs[j].Name);
                }
                return succes;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 目录、文件删除
        /// </summary>
        /// <param name="files"></param>
        /// <param name="deleteSelf"></param>
        /// <returns></returns>
        public static bool DeleteFolder(string files, bool deleteSelf = true)
        {
            var success = true;
            try
            {
                if (Directory.Exists(files))
                {
                    var fileNames = Directory.GetFiles(files, "*.*", SearchOption.AllDirectories);
                    foreach (var fileName in fileNames)
                    {
                        File.Delete(fileName);
                    }

                    var fileFolders = Directory.GetDirectories(files, "*", SearchOption.TopDirectoryOnly);
                    foreach (var fileFolder in fileFolders)
                    {
                        success = success && DeleteFiles(fileFolder);
                    }
                    if (deleteSelf)
                    {
                        Directory.Delete(files);
                    }
                }
                else if (File.Exists(files))
                {
                    File.Delete(files);
                }
                success = true;
            }
            catch (Exception)
            {
                success = false;
            }
            return success;
        }


        /// <summary>
        /// 目录或文件删除
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public static bool DeleteFiles(string files)
        {
            var success = true;
            try
            {
                if (Directory.Exists(files))
                {
                    var fileNames = Directory.GetFiles(files, "*.*", SearchOption.AllDirectories);
                    foreach (var fileName in fileNames)
                    {
                        File.Delete(fileName);
                    }

                    var fileFolders = Directory.GetDirectories(files, "*", SearchOption.TopDirectoryOnly);
                    foreach (var fileFolder in fileFolders)
                    {
                        success = success && DeleteFiles(fileFolder);
                    }
                    Directory.Delete(files);
                }
                else if (File.Exists(files))
                {
                    File.Delete(files);
                }
                success = true;
            }
            catch (Exception)
            {
                success = false;
            }
            return success;
        }

        /// <summary>
        /// 多文件删除
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public static bool DeleteMultipleFiles(string[] files)
        {
            var success = true;
            foreach (var file in files)
            {
                success = success && DeleteFiles(file);
            }
            return success;
        }

        /// <summary>
        /// 检查文件是否存在且不为空
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="deleteNull">是否删除空文件</param>
        /// <returns></returns>
        public static bool CheckFileNotNull(string filePath, bool deleteNull = false)
        {
            var reutrn = false;
            try
            {
                if (File.Exists(filePath))
                {
                    var fileInfo = new FileInfo(filePath);
                    if (fileInfo.Length <= 0 && deleteNull)
                        fileInfo.Delete();
                    else
                    {
                        reutrn = true;
                    }
                }
            }
            catch
            {
                reutrn = false;
            }
            return reutrn;
        }

    }
}
